import com.le.sarrs.util.SecurityUtil
import com.le.sarrs.util.SpringUtil
import com.le.sarrs.util.Strings
import com.mongodb.util.JSON
import net.minidev.json.JSONObject
import org.apache.commons.fileupload.servlet.ServletFileUpload
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.math.NumberUtils
import org.springframework.web.util.UrlPathHelper

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.lang.reflect.Method

def helper = new UrlPathHelper()
def reqURI = helper.getOriginatingRequestUri(request as HttpServletRequest)
reqURI = reqURI.substring(reqURI.indexOf(")") + 2, reqURI.length() - 3)

//上传log 不过滤 不处理
if (!reqURI.contains("sys/log")) {
    paserReq(request as HttpServletRequest)
}

// 安全验证白名单
def whiteList = ["rec"] as String[]
System.out.print(StringUtils.indexOfAny(reqURI, whiteList))
System.out.println()
System.out.println(reqURI)
if (StringUtils.indexOfAny(reqURI, whiteList) == -1) {
    def authCode = authCheck(request)
    if (0 != authCode) {
        def rep = (HttpServletResponse) response
        rep.setCharacterEncoding("UTF-8")
        rep.setHeader("errorCode", authCode.toString())
        rep.setHeader("errorMsg", URLEncoder.encode(500 == authCode ? "服务器错误" : "由于手机设置的时间与实际时间不符，暂不能进行任何操作，请重新设置手机时间", "UTF-8"))
        return
    }
}

def arr = reqURI.split("/")
def method = arr[1]
def clsName = arr[0]
def clsNameUpper = clsName[0].toUpperCase() + clsName[1..-1]

System.out.println(clsName + "-"+clsNameUpper)

def ctlClass
try {
    ctlClass = Class.forName("com.le.sarrs.web.controller.${clsNameUpper}Controller")
} catch (Exception ignored) {
    print 404
    return
}

show(SpringUtil.get("${clsName}Controller"), ctlClass, method, request, response)

def authCheck(request) {
    def oh = Strings.toString(request.getParameter("oh"))
    if (StringUtils.isBlank(oh)) return 500
    def s = oh.split("_")
    if (null == s || s.size() != 3) return 500
    def sid = s[0]
    def time = NumberUtils.toLong(s[1])
    def auth = s[2]
    def key = "yYER!@UO-L#F13^Ey!@"
    if (System.currentTimeMillis() - time > 1800000) {
        return 501
    }
    if (!auth.equals(StringUtils.substring(SecurityUtil.md5(StringUtils.substring(SecurityUtil.md5(sid + '_' + time + key), 0, 12)), 0, 16)))
        return 500
    return 0
}

def paserReq(HttpServletRequest request) {
    if (ServletFileUpload.isMultipartContent(request))
        return
    try {
        InputStream inputStream = request.getInputStream()
        ByteArrayOutputStream bo = new ByteArrayOutputStream()
        def temp = new byte[1024]
        int sin
        while ((sin = inputStream.read(temp)) > 0) {
            bo.write(temp, 0, sin)
        }
        byte[] reqParam = bo.toByteArray()
        // 将字节转换为字符
        def json = URLDecoder.decode(new String(reqParam, "UTF-8"), "UTF-8")
        if (!StringUtils.isBlank(json)) {
            JSONObject params = JSON.parse(json) as JSONObject
            params.each {
                request.setAttribute(filterString(it.key), filterString(Strings.toString(it.value)))
            }
        }
    } catch (Exception ignored) {
        // 解析失败的不做任何处理
    }
}

def show(ctl, Class cls, String methodName, request, response) {
    Method method
    try {
        method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class)
    }
    catch (Exception ignored) {
        print 404
        return
    }
    if (method.returnType.equals(String.class))
        print ctl."$methodName"(request, response)
    else
        ctl."$methodName"(request, response)
}

def filterString(String value) {
    if (StringUtils.isBlank(value)) {
        return value
    }
    //因传递的是对象的序列化，值中的双引号未过滤
    def search = ["&", "\\(", "\\)", "script", "<", ">", "'"] as String[]
    def replace = ["", "", "", "", "&gt", "&lt", "‘"] as String[]
    return StringUtils.replaceEach(String.valueOf(value), search, replace)
}
